/**
 * @description 微博 @ 用户关系 services
 * @author chengpeng
 */

const {
    AtRelation,
    Blog,
    User
} = require('../db/model/index')
const {
    formatUser,
    formatBlog
} = require('./_format')

/**
 * @description 微博 @ 用户关系
 * @author chengpeng
 * @param {number} blogId 
 * @param {number} userId 
 */
async function createAtRelation(blogId, userId) {
    const result = await AtRelation.create({
        blogId,
        userId
    })
    return result.dataValues
}

/**
 * @description 获取 @ 用户微博数量
 * @author chengpeng
 * @param {number} userId 
 */
async function getAtRelationCount(userId) {
    const result = await AtRelation.findAndCountAll({
        where: {
            userId,
            isRead: false
        }
    })

    return result.count
}

/**
 * @description 获取 @ 用户的微博列表
 * @author chengpeng
 * @param {object} param0 查询条件
 */
async function getAtUserBlogList({
    userId,
    pageIndex,
    pageSize = 10
}) {
    const result = await Blog.findAndCountAll({
        limit: pageSize,
        offset: pageSize * pageIndex,
        order: [
            ['id', 'desc']
        ],
        include: [
            // @ 关系
            {
                model: AtRelation,
                attributes: ['userId', 'blogId'],
                where: {
                    userId
                }
            },
            // user
            {
                model: User,
                attributes: ['userName', 'nickName', 'picture']
            }
        ]
    })

    let blogList = result.rows.map(item => item.dataValues)
    blogList = formatBlog(blogList)
    blogList = blogList.map(item => {
        item.user = formatUser(item.user.dataValues)
        return item
    })

    return {
        count: result.count,
        blogList
    }
}

/**
 * @description 更新已读
 * @author chengpeng
 * @param {object} param0 更新内容
 * @param {object} param1 更新条件
 */
async function updateAtRelation({
    newIsRead
}, {
    userId,
    isRead
}) {
    // 拼接更新内容
    const updateData = {}
    if (newIsRead) {
        updateData.isRead = newIsRead
    }
    // 拼接查询条件
    const whereData = {}
    if (userId) {
        whereData.userId = userId
    }
    if (isRead) {
        whereData.isRead = isRead
    }
    // 执行更新
    const result = await AtRelation.update(updateData, {
        where: whereData
    })

    return result[0] > 0
}

module.exports = {
    createAtRelation,
    getAtRelationCount,
    getAtUserBlogList,
    updateAtRelation
}